package com.attendancesystem.controller;

import com.attendancesystem.model.Grade;
import com.attendancesystem.service.GradesService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;



import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.List;

@WebServlet(name = "GetGradesController", value = "/GetGradesController")
public class GetGradesController extends HttpServlet {
    private static final ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        GradesService gradesService = new GradesService();
        try {
            List<Grade> grades = gradesService.getGrades();
            request.setAttribute("courses", grades);
            System.out.println("grades:"+grades);
            String jsonResponse = mapper.writeValueAsString(grades);

            // 发送JSON响应
            response.getWriter().write(jsonResponse);
            response.getWriter().flush(); //

        } catch (SQLException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            throw new RuntimeException(e);
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           doGet(request,response);
    }
}
